<%#
 Copyright 2013-2019 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
<%_
    let entityActionName = entityInstance.toUpperCase();
    let entityActionNamePlural = entityInstancePlural.toUpperCase();
_%>
import axios from 'axios';
import {
  <%_ if (searchEngine === 'elasticsearch') { _%>
  ICrudSearchAction,
  <%_ } _%>
  <%_ if (pagination === 'infinite-scroll') { _%>
  parseHeaderForLinks, loadMoreDataWhenScrolled,
  <%_ } _%>
  ICrudGetAction, ICrudGetAllAction, ICrudPutAction, ICrudDeleteAction
} from 'react-jhipster';

import { cleanEntity } from 'app/shared/util/entity-utils';
import { REQUEST, SUCCESS, FAILURE } from 'app/shared/reducers/action-type.util';
<%_ if (!(applicationType === 'gateway' && locals.microserviceName) && authenticationType !== 'uaa') { _%>

<%_ } _%>
<%_ if (fieldsContainDate) { _%>

<%_ } _%>
import { I<%= entityReactName %>, defaultValue } from 'app/shared/model/<%= entityModelFileName %>.model';

export const ACTION_TYPES = {
  <%_ if (searchEngine === 'elasticsearch') { _%>
  SEARCH_<%= entityActionNamePlural %>: '<%= entityInstance %>/SEARCH_<%= entityActionNamePlural %>',
  <%_ } _%>
  FETCH_<%= entityActionName %>_LIST: '<%= entityInstance %>/FETCH_<%= entityActionName %>_LIST',
  FETCH_<%= entityActionName %>:  '<%= entityInstance %>/FETCH_<%= entityActionName %>',
  CREATE_<%= entityActionName %>: '<%= entityInstance %>/CREATE_<%= entityActionName %>',
  UPDATE_<%= entityActionName %>: '<%= entityInstance %>/UPDATE_<%= entityActionName %>',
  DELETE_<%= entityActionName %>: '<%= entityInstance %>/DELETE_<%= entityActionName %>',
  <%_ if (fieldsContainBlob) { _%>
  SET_BLOB: '<%= entityInstance %>/SET_BLOB',
  <%_ } _%>
  RESET: '<%= entityInstance %>/RESET'
};

const initialState = {
  loading: false,
  errorMessage: null,
  entities: [] as ReadonlyArray<I<%= entityReactName %>>,
  entity: defaultValue,
  <%_ if (pagination === 'infinite-scroll') { _%>
  links: { next: 0 },
  <%_ } _%>
  updating: false,
  <%_ if (pagination !== 'no') { _%>
  totalItems: 0,
  <%_ } _%>
  updateSuccess: false
};

export type <%= entityReactName %>State =  Readonly<typeof initialState>;

// Reducer

export default (state: <%= entityReactName %>State = initialState, action): <%= entityReactName %>State => {
  switch (action.type) {
    <%_ if (searchEngine === 'elasticsearch') { _%>
    case REQUEST(ACTION_TYPES.SEARCH_<%= entityActionNamePlural %>):
    <%_ } _%>
    case REQUEST(ACTION_TYPES.FETCH_<%= entityActionName %>_LIST):
    case REQUEST(ACTION_TYPES.FETCH_<%= entityActionName %>):
      return {
        ...state,
        errorMessage: null,
        updateSuccess: false,
        loading: true
      };
    case REQUEST(ACTION_TYPES.CREATE_<%= entityActionName %>):
    case REQUEST(ACTION_TYPES.UPDATE_<%= entityActionName %>):
    case REQUEST(ACTION_TYPES.DELETE_<%= entityActionName %>):
      return {
        ...state,
        errorMessage: null,
        updateSuccess: false,
        updating: true
      };
    <%_ if (searchEngine === 'elasticsearch') { _%>
    case FAILURE(ACTION_TYPES.SEARCH_<%= entityActionNamePlural %>):
    <%_ } _%>
    case FAILURE(ACTION_TYPES.FETCH_<%= entityActionName %>_LIST):
    case FAILURE(ACTION_TYPES.FETCH_<%= entityActionName %>):
    case FAILURE(ACTION_TYPES.CREATE_<%= entityActionName %>):
    case FAILURE(ACTION_TYPES.UPDATE_<%= entityActionName %>):
    case FAILURE(ACTION_TYPES.DELETE_<%= entityActionName %>):
      return {
        ...state,
        loading: false,
        updating: false,
        updateSuccess: false,
        errorMessage: action.payload
      };
    <%_ if (searchEngine === 'elasticsearch') { _%>
    case SUCCESS(ACTION_TYPES.SEARCH_<%= entityActionNamePlural %>):
    <%_ } _%>
    case SUCCESS(ACTION_TYPES.FETCH_<%= entityActionName %>_LIST):
      <%_ if (pagination === 'infinite-scroll') { _%>
      const links = parseHeaderForLinks(action.payload.headers.link);
      <%_ } _%>
      return {
        ...state,
        <%_ if (pagination === 'infinite-scroll') { _%>
        links,
        <%_ } _%>
        loading: false,
        <%_ if (pagination !== 'no') { _%>
        totalItems: action.payload.headers['x-total-count'],
        <%_ } _%>
        <%_ if (pagination === 'infinite-scroll') { _%>
        entities: loadMoreDataWhenScrolled(state.entities, action.payload.data, links)
        <%_ } else { _%>
        entities: action.payload.data
        <%_ } _%>
      };
    case SUCCESS(ACTION_TYPES.FETCH_<%= entityActionName %>):
      return {
        ...state,
        loading: false,
        entity: action.payload.data
      };
    case SUCCESS(ACTION_TYPES.CREATE_<%= entityActionName %>):
    case SUCCESS(ACTION_TYPES.UPDATE_<%= entityActionName %>):
      return {
        ...state,
        updating: false,
        updateSuccess: true,
        entity: action.payload.data
      };
    case SUCCESS(ACTION_TYPES.DELETE_<%= entityActionName %>):
      return {
        ...state,
        updating: false,
        updateSuccess: true,
        entity: {}
      };
    <%_ if (fieldsContainBlob) { _%>
    case ACTION_TYPES.SET_BLOB:
      const { name, data, contentType } = action.payload;
      return {
        ...state,
        entity: {
          ...state.entity,
          [name]: data,
          [name + 'ContentType']: contentType
        }
      };
    <%_ } _%>
    case ACTION_TYPES.RESET:
      return {
        ...initialState
      };
    default:
      return state;
  }
};

const apiUrl = '<% if (applicationType === 'gateway' && locals.microserviceName) { %>services/<%= microserviceName.toLowerCase() %>/<% } %>api/<%= entityApiUrl %>';
<%_ if (searchEngine === 'elasticsearch') { _%>
const apiSearchUrl = '<% if (applicationType === 'gateway' && locals.microserviceName) { %>services/<%= microserviceName.toLowerCase() %>/<% } %>api/_search/<%= entityApiUrl %>';
<%_ } _%>

// Actions

<%_ if (searchEngine === 'elasticsearch') { _%>
export const getSearchEntities: ICrudSearchAction<I<%= entityReactName %>> = (query, page, size, sort) => ({
  type: ACTION_TYPES.SEARCH_<%= entityActionNamePlural %>,
<%_ if (pagination !== 'no') { _%>
  payload: axios.get<I<%= entityReactName %>>(`${apiSearchUrl}?query=${query}${sort ? `&page=${page}&size=${size}&sort=${sort}` : ''}`)
<%_ } else { _%>
  payload: axios.get<I<%= entityReactName %>>(`${apiSearchUrl}?query=${query}`)
<%_ } _%>
});

<%_ } _%>
export const getEntities: ICrudGetAllAction<I<%= entityReactName %>> = (page, size, sort) =>
<%_ if (pagination !== 'no') { _%>
{
  const requestUrl = `${apiUrl}${sort ? `?page=${page}&size=${size}&sort=${sort}` : ''}`;
  return {
    type: ACTION_TYPES.FETCH_<%= entityActionName %>_LIST,
    payload: axios.get<I<%= entityReactName %>>(`${requestUrl}${sort ? '&' : '?'}cacheBuster=${new Date().getTime()}`)
  }
}
<%_ } else { _%>
({
  type: ACTION_TYPES.FETCH_<%= entityActionName %>_LIST,
  payload: axios.get<I<%= entityReactName %>>(`${apiUrl}?cacheBuster=${new Date().getTime()}`)
});
<%_ } _%>

export const getEntity: ICrudGetAction<I<%= entityReactName %>> = id => {
  const requestUrl = `${apiUrl}/${id}`;
  return {
    type: ACTION_TYPES.FETCH_<%= entityActionName %>,
    payload: axios.get<I<%= entityReactName %>>(requestUrl)
  };
};

export const createEntity: ICrudPutAction<I<%= entityReactName %>> = entity => async dispatch => {
  const result = await dispatch({
    type: ACTION_TYPES.CREATE_<%= entityActionName %>,
    payload: axios.post(apiUrl, cleanEntity(entity))
  });
  <%_ if (pagination !== 'infinite-scroll') { _%>
  dispatch(getEntities());
  <%_ } _%>
  return result;
};

export const updateEntity: ICrudPutAction<I<%= entityReactName %>> = entity => async dispatch => {
  const result = await dispatch({
    type: ACTION_TYPES.UPDATE_<%= entityActionName %>,
    payload: axios.put(apiUrl, cleanEntity(entity))
  });
  <%_ if (pagination !== 'infinite-scroll') { _%>
  dispatch(getEntities());
  <%_ } _%>
  return result;
};

export const deleteEntity: ICrudDeleteAction<I<%= entityReactName %>> = id => async dispatch => {
  const requestUrl = `${apiUrl}/${id}`;
  const result = await dispatch({
    type: ACTION_TYPES.DELETE_<%= entityActionName %>,
    payload: axios.delete(requestUrl)
  });
  <%_ if (pagination !== 'infinite-scroll') { _%>
  dispatch(getEntities());
  <%_ } _%>
  return result;
};

<%_ if (fieldsContainBlob) { _%>
export const setBlob = (name, data, contentType?) => ({
  type: ACTION_TYPES.SET_BLOB,
  payload: {
    name,
    data,
    contentType
  }
});
<%_ } _%>

export const reset = () => ({
  type: ACTION_TYPES.RESET
});
